<?php
/**
 * User: Paulo Fournier
 * Date: --2013
 * Type: application/json
 * Used to retrieve the driver's detail JSON document
 */

require_once '../../../../php/settings/config.php';
require_once '../../../../php/lib/user.php';
require_once '../../../../php/lib/latlong.php';

session_start();

$user = unserialize($_SESSION["user"]);
$mobile = unserialize($_SESSION["mobile"]);

$mid = (int)$_POST["id"];
$point = new LatLong($mobile[$mid]["latitude"], $mobile[$mid]["longitude"]);
$data = array();
error_log($mid." => ".json_encode($point));
$tmp = array();


    foreach ($mobile as $id => $mob) {

        if($id == $mid)
            continue;

        try {

            $p = new LatLong($mob["latitude"], $mob["longitude"]);
            $dist = LatLong::distHaversine($point, $p);

            $data[] = array(
                "id" => $id,
                "reference" => $mob["reference"],
                "latitude" => $mob["latitude"],
                "longitude" => $mob["longitude"],
                "distance" => $dist * 1000
            );

        } catch (Exception $e) {
            error_log($e->getMessage());
        }
    }

/***
 * Used to sort the data object per distance
 * @param $a
 * @param $b
 * @return int
 */
function distanceSort($a, $b){
    $a = $a['distance'];
    $b = $b['distance'];
    if ($a == $b)
        return 0;
    return ($a < $b) ? -1 : 1;
}

usort($data, "distanceSort");
$data = array_slice($data, 0, 7);

for($i=0; $i<sizeof($data); $i++){

    $g = sprintf("http://maps.googleapis.com/maps/api/directions/json?sensor=false&origin=%f,%f&destination=%f,%f", $data[$i]["latitude"], $data[$i]["longitude"], $mobile[$mid]["latitude"], $mobile[$mid]["longitude"]);

    $dir = json_decode(file_get_contents($g),true);

    if($dir["status"] == "OK"){

        $data[$i] = array_merge($data[$i],array(
            "bounds" => $dir["routes"][0]["bounds"],
            "polyline" => $dir["routes"][0]["overview_polyline"]["points"],
            "distance" => $dir["routes"][0]["legs"][0]["distance"]["value"],
            "duration" => $dir["routes"][0]["legs"][0]["duration"]["value"]
        ));

    }

}

echo json_encode($data);